package com.lgy.ms.core.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {
    private static Log log = LogFactory.getLog(MD5Util.class);

    public MD5Util() {
    }

    public static String encrypt(File file) throws IOException {
        FileInputStream in = new FileInputStream(file);
        FileChannel ch = in.getChannel();
        MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0L, file.length());
        MessageDigest messagedigest = null;

        try {
            messagedigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException var6) {
            log.error("初始化失败，MessageDigest不支持MD5Util，原因是：" + var6.getMessage(), var6);
        }

        messagedigest.update(byteBuffer);
        return DataFormater.byte2hex(messagedigest.digest());
    }

    public static String encrypt(String s) {
        try {
            return encrypt(s.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException var2) {
            log.error("密码验证出异常了", var2);
            return "";
        }
    }

    public static String encrypt(byte[] bytes) {
        MessageDigest messagedigest = null;

        try {
            messagedigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException var3) {
            log.error("初始化失败，MessageDigest不支持MD5Util，原因是：" + var3.getMessage(), var3);
        }

        messagedigest.update(bytes);
        return DataFormater.byte2hex(messagedigest.digest());
    }

    public static boolean checkPassword(String password, String md5PwdStr) {
        String s = "";
        s = encrypt(password);
        return s.equals(md5PwdStr);
    }
}